<template>
  <div class="import-flow route-page">
    <section class="header">
      <a-page-header title="导入流水" @back="goBack">
        <template #extra>
          <a-button
            key="2"
            type="primary"
            ghost
            @click="editTemplate"
            v-if="currentStep == 0"
            >流水模板管理</a-button
          >
          <a-button key="1" type="primary" ghost @click="toFlowRecord"
            >查看导入记录</a-button
          >
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <a-card style="min-height: 100%">
        <a-alert
          message="【企业客户将银行流水上传】银行流水通过自定义模板匹配系统项，建立银行流水Excel行列与系统项的对应关系"
          type="info"
          closable
        />

        <!-- step -->
        <a-row class="mt-20">
          <a-col :span="12" :offset="6">
            <a-steps :current="currentStep" style="margin-top: 20px">
              <a-step
                v-for="item in steps"
                :key="item.title"
                :title="item.title"
              />
            </a-steps>
          </a-col>
        </a-row>

        <!-- 内容区域 -->
        <div v-if="spinning" class="spinning-wrap">
          <a-spin size="large" />
        </div>
        <template v-else-if="currentStep == 0">
          <a-row class="mt-20">
            <a-col :span="12" :offset="6">
              <a-form style="margin-top: 20px">
                <a-form-item
                  label="导入文件"
                  v-bind="validateInfos.template_path"
                >
                  <a-upload-dragger
                    v-model:fileList="fileList"
                    name="file"
                    :multiple="false"
                    :action="$utils.fileAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    :showUploadList="false"
                    @change="handleUploadChange"
                    accept=".xlsx"
                    :key="uploadKey"
                  >
                    <template v-if="fileList.length">
                      <p class="ant-upload-drag-icon">
                        <FileTextOutlined />
                      </p>
                      <p class="ant-upload-text">
                        {{ fileList[0].name }}
                      </p>
                    </template>
                    <template v-else>
                      <p class="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                      <p class="ant-upload-text">
                        拖拽文件至虚线款内或点击此区域上传文件
                      </p>
                      <p class="ant-upload-hint">
                        文档只支持XLSX 工作表 (.xlsx)
                      </p>
                    </template>
                  </a-upload-dragger>
                </a-form-item>
                <a-form-item
                  label="流水模板"
                  v-bind="validateInfos.template_id"
                >
                  <a-select
                    v-model:value="formRef.template_id"
                    :options="
                      templateList.map((item) => ({
                        label: item.name,
                        value: item.id,
                        item: item,
                      }))
                    "
                    optionLabelProp="label"
                    allowClear
                    @change="onTemplateIdChange"
                    :dropdownStyle="{ zIndex: 999 }"
                  >
                    <template #option="{ value: val, label }">
                      <div
                        style="
                          display: flex;
                          justify-content: space-between;
                          align-items: center;
                          padding-right: 10px;
                        "
                      >
                        <div>{{ label }}</div>
                        <EyeOutlined @click.stop="editTemplate(val)" />
                      </div>
                    </template>
                    <template #dropdownRender="{ menuNode: menu }">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0" />
                      <a-row
                        justify="center"
                        @click="editTemplate(-1)"
                        @mousedown="(e) => e.preventDefault()"
                        style="cursor: pointer"
                      >
                        <a-button type="link">
                          <template #icon><PlusOutlined /></template>
                          新增模板
                        </a-button>
                      </a-row>
                    </template>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="是否自动匹配账单"
                  v-bind="validateInfos.auto_match"
                >
                  <a-radio-group
                    v-model:value="formRef.auto_match"
                    @change="onMatchChange"
                  >
                    <a-radio :value="1">匹配</a-radio>
                    <a-radio :value="2">不匹配</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-form>
              <a-row class="mt-20" justify="center">
                <a-button
                  type="primary"
                  @click="nextStep"
                  :loading="step1Loading"
                  :disabled="step1Disabled"
                >
                  下一步
                </a-button>
              </a-row>
            </a-col>
          </a-row>
        </template>
        <template v-else-if="currentStep == 1 || currentStep == 2">
          <a-row class="mt-20" justify="center">
            <a-col :span="24" style="display: flex; justify-content: center">
              <div class="template-table">
                <div class="template-table-name">
                  {{ currentTemplateName }}
                  <span class="template-table-name-tip">
                    备注：红色字体为必填项
                  </span>
                </div>
                <div class="template-table-content">
                  <div class="template-table-head">
                    <div
                      v-for="(item, index) of currentTemplateHead"
                      :key="index"
                      class="template-table-head-item"
                      :style="{
                        width:
                          index == currentTemplateHead.length - 1 &&
                          currentStep == 1
                            ? '453px'
                            : '150px',
                        minWidth:
                          index == currentTemplateHead.length - 1 &&
                          currentStep == 1
                            ? '453px'
                            : '150px',
                        flex:
                          currentTemplateHead.length <= 8 ||
                          (index == currentTemplateHead.length - 1 &&
                            currentStep == 2)
                            ? 1
                            : '',
                        color:
                          item.key == 'loan_type' ||
                          item.key == 'income_date' ||
                          item.key == 'company_name' ||
                          item.key == 'other_account' ||
                          item.key == 'amount' ||
                          item.key == 'voucher_no' ||
                          item.key == 'match_line'
                            ? 'red'
                            : '',
                      }"
                    >
                      {{ item.name }}
                    </div>
                  </div>
                  <div class="template-table-body">
                    <div
                      class="template-table-line"
                      v-for="(item, index) of currentTemplateBody"
                      :key="index"
                    >
                      <template
                        v-if="item.matchedData && item.matchedData.length > 0"
                      >
                        <div
                          v-for="(item, index) of item.matchedData"
                          :key="index"
                          class="template-table-body-item"
                          :style="{
                            flex: currentTemplateHead.length <= 8 ? 1 : '',
                          }"
                        >
                          <a-tooltip>
                            <template #title>{{ item }}</template>
                            {{ item }}
                          </a-tooltip>
                        </div>
                        <!-- 第二步 -->
                        <template v-if="currentStep == 1">
                          <div
                            class="template-table-body-item"
                            style="width: 453px; min-width: 453px"
                            :style="{
                              flex: currentTemplateHead.length <= 8 ? 1 : '',
                            }"
                          >
                            <span v-if="item.error">
                              <a-tooltip>
                                <template #title>
                                  {{ item.error }}
                                  <span
                                    style="color: #2681f3; cursor: pointer"
                                    v-if="item.stream_id"
                                    @click="toStreamDetail(item.stream_id)"
                                    >【查看】
                                  </span>
                                </template>
                                {{ item.error }}
                                <span
                                  style="color: #2681f3; cursor: pointer"
                                  v-if="item.stream_id"
                                  @click="toStreamDetail(item.stream_id)"
                                  >【查看】
                                </span>
                              </a-tooltip>
                            </span>
                          </div>
                        </template>
                        <!-- 第三步 -->
                        <template v-if="currentStep == 2">
                          <div
                            class="template-table-body-item"
                            :style="{
                              flex: currentTemplateHead.length <= 10 ? 1 : '',
                            }"
                          >
                            <span
                              v-if="item.stream_id && !item.error"
                              style="color: #52c41a"
                            >
                              成功；
                              <span
                                style="cursor: pointer"
                                @click="toStreamDetail(item.stream_id)"
                                >【查看流水详情】
                              </span>
                            </span>
                            <span style="color: red" v-else>失败</span>
                          </div>
                        </template>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>
            <a-col
              :span="24"
              style="display: flex; justify-content: center; margin-top: 20px"
              v-if="currentStep == 1"
            >
              <a-button @click="currentStep = 0"> 上一步 </a-button>
              <a-button
                type="primary"
                @click="submitImport"
                :loading="step2Loading"
                style="margin-left: 20px"
              >
                生成流水
              </a-button>
            </a-col>
            <a-col
              :span="24"
              style="display: flex; justify-content: center; margin-top: 20px"
              v-if="currentStep == 2"
            >
              <a-button type="primary" @click="goBack"> 确定 </a-button>
            </a-col>
          </a-row>
        </template>
      </a-card>
    </section>

    <FlowTemplateModal
      :visible="editTemplateVisible"
      :id="editTemplateId"
      @onClose="editTemplateVisible = false"
      @refresh="onFlowTemplateModalChange"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  onBeforeUnmount,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { useRouter, useRoute } from "vue-router";
// import { PlusOutlined } from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import moment from "moment";
import FlowTemplateModal from "./modules/FlowTemplateModal.vue";
import {
  FileTextOutlined,
  InboxOutlined,
  EyeOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "importBillFlow",
  components: {
    FileTextOutlined,
    InboxOutlined,
    EyeOutlined,
    PlusOutlined,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    FlowTemplateModal,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const goBack = () => {
      // state.currentStep = 0;
      // resetFields();
      // checkStep1Form();
      // state.fileList = [];
      // state.currentTemplateName = "";
      // state.currentTemplateHead = [];
      // state.currentTemplateBody = [];
      $router.back();
    };

    const state = reactive({
      steps: [
        {
          title: "上传文件",
          content: "",
        },
        {
          title: "生成流水",
          content: "",
        },
        {
          title: "结果反馈",
          content: "",
        },
      ],
      currentStep: 0,

      fileList: [],
      templateList: [],

      editTemplateId: 0,
      editTemplateVisible: false,

      step1Loading: false,
      step1Disabled: true,
      step2Loading: false,

      currentTemplateName: "", //当前选用导入的模板名称
      currentTemplateHead: [], //预览模板的表头
      currentTemplateBody: [], //预览模板的表内容
      templateContent: [], //模板内容

      spinning: false,
      uploadKey: 0,
    });

    const formRef = reactive({
      template_path: "",
      template_id: null,
      auto_match: null,
    });

    const ruleRef = reactive({
      template_path: [{ required: true, message: "必填项" }],
      template_id: [{ required: true, message: "必填项" }],
      auto_match: [{ required: true, message: "必填项" }],
    });

    const { resetFields, validate, validateInfos } = useForm(formRef, ruleRef);

    // 请求模板列表
    const getTemplateList = (refresh) => {
      request.get("/org", "/stream/templateList").then((res) => {
        state.templateList = res.list;
        if (res.list.length == 1) {
          formRef.template_id = res.list[0].id;
          state.currentTemplateName = res.list[0].name;
          state.templateContent = res.list[0].content;
        }

        // 模板列表变化时，匹配并更新当前选中项
        let currentTemplateInList = false;
        if (refresh && formRef.template_id) {
          res.list.forEach((item) => {
            if (item.id == formRef.template_id) {
              currentTemplateInList = true;
              onTemplateIdChange(item.id, { item: item });
            }
          });
        }
        // 如果当前选中模板不在列表中，说明被删除，需要手动删除已选中，重新选择
        if (refresh && !currentTemplateInList) {
          formRef.template_id = null;
          state.currentTemplateName = "";
          state.currentTemplateHead = [];
          state.templateContent = [];
          checkStep1Form();
        }
      });
    };

    // 新增、编辑模板
    const editTemplate = (id) => {
      state.editTemplateId = 0;
      if (id && (id > 0 || id == -1)) {
        state.editTemplateId = id;
      }
      state.editTemplateVisible = true;
    };

    //上传文件
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              formRef.template_path = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        formRef.template_path = "";
      }
      state.fileList = resFileList;
      checkStep1Form();
    };

    const onTemplateIdChange = (value, option) => {
      state.currentTemplateName = option.item.name;
      state.templateContent = option.item.content;
      checkStep1Form();
    };

    const onMatchChange = () => {
      checkStep1Form();
    };

    const checkStep1Form = () => {
      if (
        formRef.template_path &&
        formRef.template_id &&
        formRef.auto_match >= 1
      ) {
        state.step1Disabled = false;
      } else {
        state.step1Disabled = true;
      }
    };

    // 下一步
    const nextStep = () => {
      state.step1Loading = true;
      state.spinning = true;
      request
        .post("/org", "/stream/templateImportVerify", {
          template_id: formRef.template_id,
          source_file: formRef.template_path,
          status: formRef.auto_match,
        })
        .then((res) => {
          state.step1Loading = false;
          state.currentStep++;

          // 1.处理表头
          let matchList = [];
          let content = JSON.parse(JSON.stringify(state.templateContent));
          content.forEach((item) => {
            // 字母A-Z转换成对应的code值
            if (item.key == "voucher_no") {
              item.row = item.row.split("+");
              item.rowCode = item.row[0].charCodeAt() - 65;
              matchList.push(item);
            } else {
              if (
                item.key != "loan_type" &&
                item.key != "currency" &&
                item.key != "match_line" &&
                item.row
              ) {
                item.rowCode = item.row.charCodeAt() - 65;
                matchList.push(item);
              }
            }
          });
          let result = [
            {
              key: "loan_type",
              row: "贷（收入）",
              name: "借贷标",
              checked: true,
            },
            { key: "currency", row: "人民币", name: "币种" },
          ];
          // 按字母A-Z从小到大排序
          matchList.sort((a, b) => {
            return a.rowCode - b.rowCode;
          });
          result = result.concat(matchList);
          result.push({
            key: "result",
            name: "匹配结果",
          });
          state.currentTemplateHead = result;

          //2.根据表头找到对应的每一列数据
          if (res.response_params && res.response_params.logList) {
            res.response_params.logList.forEach((item) => {
              if (item.data) {
                item.matchedData = [];

                state.currentTemplateHead.forEach((headItem) => {
                  if (headItem.rowCode >= 0) {
                    item.matchedData.push(item.data[headItem.rowCode]);
                  }
                });

                item.matchedData.unshift("贷（收入）", "人民币");
              }
            });
            state.currentTemplateBody = res.response_params.logList;
            state.spinning = false;
          }
        })
        .catch((err) => {
          state.step1Loading = false;
        });
    };

    // 前往导入记录
    const toFlowRecord = () => {
      $router.push({ name: "billFlowImportRecord" });
    };

    // 前往流水详情
    const toStreamDetail = (stream_id) => {
      $router.push({ name: "turnoverDetail", query: { tId: stream_id } });
    };

    // 生成流水
    const submitImport = () => {
      state.step2Loading = true;
      state.spinning = true;
      request
        .post("/org", "/stream/templateImport", {
          template_id: formRef.template_id,
          source_file: formRef.template_path,
          status: formRef.auto_match,
        })
        .then((res) => {
          state.step2Loading = false;
          state.currentStep++;

          //2.根据表头找到对应的每一列数据
          if (res.importResult && res.importResult.logId) {
            getImportDetail(formRef.template_id, res.importResult.logId);
          }
        })
        .catch((err) => {
          state.step2Loading = false;
        });
    };

    // 导入详情
    const getImportDetail = (template_id, log_id) => {
      request
        .get("/org", "/stream/templateImportDetail", {
          template_id: template_id,
          log_id: log_id,
        })
        .then((res) => {
          if (
            res.logData &&
            res.logData.response_params &&
            res.logData.response_params.logList
          ) {
            res.logData.response_params.logList.forEach((item) => {
              if (item.data) {
                item.matchedData = [];

                state.currentTemplateHead.forEach((headItem) => {
                  if (headItem.rowCode >= 0) {
                    console.log(headItem.name, item.data[headItem.rowCode]);
                    item.matchedData.push(item.data[headItem.rowCode]);
                  }
                });

                item.matchedData.unshift("贷（收入）", "人民币");
              }
            });
            state.currentTemplateBody = res.logData.response_params.logList;
            state.spinning = false;
          }
        });
    };

    // 模板列表变化时
    const onFlowTemplateModalChange = () => {
      getTemplateList(true);
    };

    // 请求模板详情
    const getTemplateDetail = (template_id, log_id) => {
      if (template_id && log_id) {
        state.spinning = true;
        request
          .get("/org", "/stream/templateDetail", {
            id: template_id,
          })
          .then((res) => {
            if (res.detail && res.detail.content) {
              // 1.处理表头
              let matchList = [];
              res.detail.content.forEach((item) => {
                // 字母A-Z转换成对应的code值
                if (item.key == "voucher_no") {
                  item.row = item.row.split("+");
                  item.rowCode = item.row[0].charCodeAt() - 65;
                  matchList.push(item);
                } else {
                  if (
                    item.key != "loan_type" &&
                    item.key != "currency" &&
                    item.key != "match_line" &&
                    item.row
                  ) {
                    item.rowCode = item.row.charCodeAt() - 65;
                    matchList.push(item);
                  }
                }
              });
              let result = [
                {
                  key: "loan_type",
                  row: "贷（收入）",
                  name: "借贷标",
                  checked: true,
                },
                { key: "currency", row: "人民币", name: "币种" },
              ];
              // 按字母A-Z从小到大排序
              matchList.sort((a, b) => {
                return a.rowCode - b.rowCode;
              });
              result = result.concat(matchList);
              result.push({
                key: "result",
                name: "匹配结果",
              });
              state.currentTemplateName = res.detail.name;
              state.currentTemplateHead = result;

              //2.根据表头找到对应的每一列数据
              getImportDetail(template_id, log_id);
            }
          });
      }
    };

    const init = () => {
      state.uploadKey = Math.random();
      setTimeout(() => {
        state.uploadKey = 0;
      }, 100);
      getTemplateList();
      if ($route.query.id && $route.query.template_id) {
        state.currentStep = 2;
        getTemplateDetail($route.query.template_id, $route.query.id);
      }
    };

    init();

    return {
      ...toRefs(state),
      goBack,
      formRef,
      validateInfos,
      editTemplate,
      handleUploadChange,
      onTemplateIdChange,
      onMatchChange,
      nextStep,
      toFlowRecord,
      toStreamDetail,
      submitImport,
      onFlowTemplateModalChange,
    };
  },
});
</script>

<style lang="less" scoped>
.import-flow {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 50px;
    background: #fff;
    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }
  &.back-class {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
  .content {
    flex: 1;
    padding: 10px;
    margin: 10px 0;
    max-height: 100%;
    overflow-y: auto;

    .template-table {
      width: 100%;
      margin: 20px 0;

      .template-table-name {
        text-align: center;
        font-size: 16px;
        height: 50px;
        line-height: 50px;
        background-color: #305496;
        color: #fff;
        position: relative;
        padding: 0 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        .template-table-name-tip {
          position: absolute;
          right: 10px;
          bottom: 10px;
          color: red;
          font-size: 12px;
          height: 12px;
          line-height: 12px;
        }
      }

      .template-table-content {
        overflow-x: auto;

        .template-table-head {
          // width: 100%;
          height: 40px;
          line-height: 40px;
          display: flex;
          font-size: 12px;

          .template-table-head-item {
            // flex: 1;
            text-align: center;
            padding: 0 10px;
            border-top: 1px solid #eee;
            border-right: 1px solid #eee;
            background-color: #f5f5f5;
            width: 150px;
            min-width: 150px;
          }

          .template-table-head-item:first-child {
            border-left: 1px solid #eee;
          }
        }

        .template-table-body {
          font-size: 12px;
          max-height: 401px;

          .template-table-line {
            // width: 100%;
            height: 40px;
            line-height: 40px;
            display: flex;

            .template-table-body-item {
              // flex: 1;
              text-align: center;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              padding: 0 10px;
              border-top: 1px solid #eee;
              border-right: 1px solid #eee;
              width: 150px;
              min-width: 150px;
            }

            .template-table-body-item:first-child {
              border-left: 1px solid #eee;
            }
          }

          .template-table-line:last-child {
            .template-table-body-item {
              border-bottom: 1px solid #eee;
            }
          }
        }
      }
    }

    .spinning-wrap {
      width: 100%;
      height: 400px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
